#!/bin/bash

# RustDesk hwcodec 硬件编解码依赖安装脚本
# 支持 Intel QSV, NVIDIA NVENC, AMD AMF

set -e

echo "🔧 安装RustDesk硬件编解码依赖..."

# 检测操作系统
if [ -f /etc/debian_version ]; then
    OS="debian"
elif [ -f /etc/redhat-release ]; then
    OS="redhat"
else
    echo "❌ 不支持的操作系统"
    exit 1
fi

install_debian_deps() {
    echo "📦 更新软件包列表..."
    sudo apt update

    echo "📦 安装基础编译依赖..."
    sudo apt install -y \
        build-essential \
        cmake \
        pkg-config \
        yasm \
        nasm

    echo "📦 安装FFmpeg开发库..."
    sudo apt install -y \
        libavcodec-dev \
        libavformat-dev \
        libavutil-dev \
        libavdevice-dev \
        libavfilter-dev \
        libswscale-dev \
        libswresample-dev

    echo "📦 安装Intel硬件加速库..."
    sudo apt install -y \
        intel-media-va-driver \
        i965-va-driver \
        vainfo \
        libva-dev \
        libva-drm2 \
        libva-x11-2

    echo "📦 尝试安装Intel Media SDK (可选)..."
    sudo apt install -y \
        libmfx1 \
        libmfx-dev || echo "⚠️  Intel Media SDK不可用，跳过"

    echo "📦 安装NVIDIA开发库 (如果有NVIDIA显卡)..."
    if command -v nvidia-smi &> /dev/null; then
        echo "🎯 检测到NVIDIA显卡"
        sudo apt install -y \
            libnvidia-encode-470-dev \
            libnvidia-decode-470-dev || \
            sudo apt install -y \
                libnvidia-encode-dev \
                libnvidia-decode-dev || \
            echo "⚠️  NVIDIA编码库安装失败，请手动安装"
    fi

    echo "📦 安装其他硬件加速库..."
    sudo apt install -y \
        libvdpau-dev \
        libxvmc-dev \
        libx11-dev
}

install_redhat_deps() {
    echo "📦 安装RHEL/CentOS/Fedora依赖..."
    
    if command -v dnf &> /dev/null; then
        PKG_MGR="dnf"
    else
        PKG_MGR="yum"
    fi

    sudo $PKG_MGR install -y \
        gcc gcc-c++ \
        cmake \
        pkg-config \
        yasm nasm \
        ffmpeg-devel \
        libva-devel \
        libvdpau-devel \
        intel-media-driver
}

# 安装依赖
case $OS in
    debian)
        install_debian_deps
        ;;
    redhat)
        install_redhat_deps
        ;;
esac

echo "🔍 验证安装结果..."

# 检查pkg-config
echo "📋 检查可用的pkg-config模块:"
pkg-config --list-all | grep -E "(libav|va|mfx)" || echo "未找到相关模块"

# 检查vainfo（Intel）
if command -v vainfo &> /dev/null; then
    echo "🎯 Intel VA-API信息:"
    vainfo 2>/dev/null | head -10 || echo "VA-API不可用"
fi

# 检查NVIDIA
if command -v nvidia-smi &> /dev/null; then
    echo "🎯 NVIDIA信息:"
    nvidia-smi --query-gpu=name,driver_version --format=csv,noheader || echo "NVIDIA信息获取失败"
fi

echo ""
echo "✅ 硬件编解码依赖安装完成!"
echo ""
echo "🚀 现在可以尝试编译硬件加速版本:"
echo "   cargo build --release --features \"cli,use_dasp,hwcodec\""
echo ""
echo "⚠️  如果仍然失败，建议使用软件编解码版本:"
echo "   ./build_server_simple.sh" 